<?php
class DigUi_View_Helper_DigUiJqueryTreeTable extends Zend_View_Helper_HtmlElement 
{  
    public $id;
    public $columns;
    public $rows;
    public $attribs;
      
    public function digUiJqueryTreeTable($id, $columns, $attribs = array())
    {
        $this->id = $this->_normalizeId($id);
        $this->columns = $columns;
        $attribs['id'] = $this->id;
        $this->attribs = $attribs;
        return $this;
    }
    
    public function addItem(DigCms_Model_Item $item, $recursive = true)
    {
        $this->addRow($item->id, $item->parent_id, $item->toArray());
        if($recursive) {
            $children = $item->children(null);
            if($children) {
                foreach ($children as $child) {
                    $this->addItem($child, $recursive);
                }
            }
        }
    }
    
    public function addRow($id, $parentId, $data = array(), $attribs = array())
    {
        $row = array(
            'id'        => $id,
            'parent_id' => $parentId,
        	'data'      => $data,
            'attribs'	=> $attribs
        );
        $this->rows[] = $row;
    }
    
    public function render()
    {
        $this->_jquery();        
        $xhtml = array();
        $this->attribs['class'] = 'ui-widget-content ui-corner-bottom';
        $xhtml[] = "<table " . $this->_htmlAttribs($this->attribs) . ">"; 
        
        // table header
        $xhtml[] = "<thead class='ui-widget-header ui-corner-all'><tr>";
        foreach ($this->columns as $key => $column) {
            $xhtml[] = '<th class="' . $key . '">' . $column . "</th>";
        }
        $xhtml[] = "</tr><thead>";
        
        // table body
        $xhtml[] = "<tbody>";
        foreach ($this->rows as $row) {
            $attribs = $row['attribs'];
            $attribs['id'] = $row['id'];
            if($row['parent_id'] != null) {
                $relatedClass = 'child-of-' . $row['parent_id'];
            }else{
                $relatedClass = null;
            }
            
            if(isset($attribs['class'])) {
                $attribs['class'] = $attribs['class'] . ' ' . $relatedClass ;
            } else {
                $attribs['class'] = $relatedClass;
            }
            $xhtml[] = '<tr ' . $this->_htmlAttribs($attribs) . '>';
            $data = $row['data'];
            foreach (array_keys($this->columns) as $key) {
                $value = isset($data[$key]) ? $data[$key] : null;
                 $xhtml[] = '<td class="' . $key . '">' . $value . '</td>';
            }
            $xhtml[] = '</tr>';
        }
        $xhtml[] = "</tbody>";
        $xhtml[] = "</table>";
        
        return implode(PHP_EOL, $xhtml) . PHP_EOL;
    }
    
    private function _jquery($sortable = false)
    {
        $this->view->jQuery()->addJavascriptFile('/jquery/jquery.treeTable.js');
        $this->view->jQuery()->addStylesheet('/css/jquery.treeTable.css');
        $this->view->jQuery()->addOnLoad('$("#' . $this->id . '").treeTable();');
        $this->view->jQuery()->onLoadCaptureStart() ?>
        	$("#<?= $this->id ?> tbody tr").hover(
        		function(){
        			$(this).find('td').addClass('ui-state-highlight');
        		},
        		function(){
        			$(this).find('td').removeClass('ui-state-highlight');
        		}
    		);
        <?php $this->view->jQuery()->onLoadCaptureEnd();
        if($sortable) {
            $this->view->jQuery()->onLoadCaptureStart() ?>
            /* NOTE: Do not forget to download the jQuery UI Draggable and Droppable
             * components if you want to enable dragging and dropping behavior!
             */
              
            // Configure draggable nodes
            $("#<?= $this->id ?> .file, #<?= $this->id ?> .folder").draggable({
              helper: "clone",
              opacity: .75,
              refreshPositions: true, // Performance?
              revert: "invalid",
              revertDuration: 300,
              scroll: true
            });
            
            // Configure droppable rows
            $("#<?= $this->id ?> .folder").each(function() {
              $(this).parents("tr").droppable({
                accept: ".file, .folder",
                drop: function(e, ui) { 
                  // Call jQuery treeTable plugin to move the branch
                  $($(ui.draggable).parents("tr")).appendBranchTo(this);
                },
                hoverClass: "accept",
                over: function(e, ui) {
                  // Make the droppable branch expand when a draggable node is moved over it.
                  if(this.id != $(ui.draggable.parents("tr")[0]).id && !$(this).is(".expanded")) {
                    $(this).expand();
                  }
                }
              });
            });
            
            // Make visible that a row is clicked
            $("table#<?= $this->id ?> tbody tr").mousedown(function() {
              $("tr.selected").removeClass("selected"); // Deselect currently selected rows
              $(this).addClass("selected");
            });
            
            // Make sure row is selected when span is clicked
            $("table#<?= $this->id ?> tbody tr span").mousedown(function() {
              $($(this).parents("tr")[0]).trigger("mousedown");
            });
            
            <?php $this->view->jQuery()->onLoadCaptureEnd();
        }
    }
}
?>